
#include <QDebug>
#include "minirobot.h"
#include "ui_minirobot.h"  // 这个应该由 uic 自动生成

MiniRobot::MiniRobot(QMainWindow *parent) : QMainWindow(parent), ui(new Ui::MiniRobot), qglplay_ptz(nullptr)
{
    ui->setupUi(this);

    // 初始化摄像头
    init_camera();
    setup_connect();
}

void MiniRobot::init_camera()
{
    // 确保CameraWidget有正确的布局
    if (!ui->CameraWidget->layout())
    {
        QVBoxLayout *layout = new QVBoxLayout(ui->CameraWidget);
        layout->setContentsMargins(0, 0, 0, 0);  // 去除边距
        ui->CameraWidget->setLayout(layout);
    }

    // 创建QGLPlayerWidget实例，并添加到CameraWidget的布局中
    qglplay_ptz = new QGLPlayerWidget(ui->CameraWidget);
    ui->CameraWidget->layout()->addWidget(qglplay_ptz);
}

void MiniRobot::start_camera_stream()
{
    if (!qglplay_ptz)
    {
        qWarning() << "QGLPlayerWidget is not initialized!";
        return;
    }

    QString rtspUrl = "rtsp://172.16.29.144:8554/0";

    qDebug() << "Attempting to connect to:" << rtspUrl;

    // 启动预览
    int result = qglplay_ptz->start_preview(rtspUrl.toStdString());
    if (result != 0)
    {
        qWarning() << "Failed to start preview, error code:" << result;
        on_camera_play_fail();
    }
}

void MiniRobot::setup_connect()
{
    // 初始化姿态指示器
    attitude_indicator = new AttitudeIndicator(ui->CameraWidget);        // 将CameraWidget作为父组件
    attitude_indicator->setAttribute(Qt::WA_TransparentForMouseEvents);  // 允许鼠标事件穿透
    attitude_indicator->setWindowFlags(Qt::Widget);                      // 确保它作为普通小部件

    // 设置姿态指示器的位置和大小
    int indicatorSize = 120;  // 根据需求调整大小
    attitude_indicator->setFixedSize(indicatorSize, indicatorSize);
    attitude_indicator->move(ui->CameraWidget->width() - indicatorSize - 10, 40);  // 右上角下移一点点

    // 确保姿态指示器显示在最上层
    attitude_indicator->raise();
    attitude_indicator->show();

    // 连接QGLPlayerWidget的信号
    if (qglplay_ptz)
    {
        connect(qglplay_ptz, &QGLPlayerWidget::sig_on_preview_start, this, &MiniRobot::on_camera_play_succeed);
        connect(qglplay_ptz, &QGLPlayerWidget::sig_on_preview_stop, this, &MiniRobot::on_camera_play_fail);
    }

    // 启动视频流
    start_camera_stream();
}

void MiniRobot::on_camera_play_succeed()
{
    qDebug() << "Camera playback started successfully";
    // 可以在这里更新UI状态，例如隐藏加载指示器
}

void MiniRobot::on_camera_play_fail()
{
    qWarning() << "Camera playback failed or stopped";
    // 可以在这里显示错误消息或尝试重新连接
    QMessageBox::warning(this, "Camera Error", "Failed to connect to camera. Please check the camera IP and credentials.");
}

MiniRobot::~MiniRobot()
{
    // 停止摄像头预览
    if (qglplay_ptz)
    {
        qglplay_ptz->stop_preview();
    }

    delete ui;
}
